#include "sinawidget.h"
#include "ui_sinawidget.h"
#include "account.h"
#include "sinaweibo.h"
#include "statuswidget.h"
#include "sinaparserxml.h"
#include "showpicture.h"
#include "SinaGlobalNamespace.h"

#include <qimagereader.h>
#include <QDir>
#include <QMessageBox>
#include <QtWebKit>
#include <QtGui>
SinaWidget::SinaWidget(Account* pAccount,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SinaWidget)
{
    ui->setupUi(this);
    this->account = pAccount;
    conf = Configuration::getInstance();
    this->ui->webView_left->setPage(new QWebPage(this));
    this->dealWebkitEvent = new DealWebkitEvent(account,this);
    this->timer = new QTimer(this);// timer
    this->pStatusWidget = NULL;
    this->currentSelected = 0;
    ui->webView_left->setHtml("<body style=\"background-color:rgb(222,222,222);font-family:微软雅黑\"></body>");
    ui->webView_right->setHtml("<body style=\"background-color:rgb(222,222,222);font-family:微软雅黑\"></body>");

    QFile basicHtmlFile(":/other/res/sina/SinaHomePage.html");
    if(!basicHtmlFile.open(QFile::ReadOnly))
    {
        qDebug("open Error!!!");
        qDebug(basicHtmlFile.errorString().toAscii());
    }
    QTextStream stream(&basicHtmlFile);
    basicHtml = stream.readAll();
    basicHtmlFile.close();

    this->homePageHtmlReady = false;
    this->homePageStatusReady = true;
    this->atMePageHtmlReady = false;
    this->atMePageStatusReady = false;
    this->commentPageHtmlReady = false;
    this->commentPageStatusReady = false;
    this->myWeiboPageHtmlReady = false;
    this->myWeiboPageStatusReady = false;
    this->favoritePageHtmlReady = false;
    this->favoritePageStatusReady = false;
    this->directMessagePageHtmlReady = false;
    this->directMessagePageStatusReady = false;

    this->publicStatusesHtmlReady = false;
    this->publicStatusesReady = false;

    this->statusUnread=0;
    this->commentsUnread=0;
    this->atMeMentionsUnread=0;
    this->directMessageUnread=0;
    this->newFollower=0;


    this->otherAccount = NULL;
    changeSelectedPixmap(1,0);
    this->currentSelected = 1;
    changeSelectedPixmap(1,1);


    QObject::connect(ui->webView_left->page()->mainFrame(),
                      SIGNAL(javaScriptWindowObjectCleared()),
                      this,
                      SLOT(addJavaScriptObject())
                      );

    QObject::connect(ui->webView_right->page()->mainFrame(),
                     SIGNAL(javaScriptWindowObjectCleared()),
                     this,
                     SLOT(addJavaScriptObject()));



    timer->setSingleShot(true);
    QObject::connect(timer,SIGNAL(timeout()), this, SLOT(prepare()));
    timer->start(500);//0.5s
}

SinaWidget::~SinaWidget()
{
    delete ui;
}

void SinaWidget::receiveSignalFromMainWidget(int index){

//    qDebug("currentIndex:"+QString::number(index).toLocal8Bit());
//    this->currentSelected = index;
    if (index == this->currentSelected)
        return ;

    if (index != 4)
    {
        changeSelectedPixmap(this->currentSelected,0);
        this->currentSelected = index;
        changeSelectedPixmap(index,1);
    }

    switch (index){
    case 1:

        homePageButtonClicked();

        break;
    case 2:
        atMePageButtonClicked();
        break;
    case 3:
        myWeiboPageButtonClicked();
        break;
    case 4:
        newWeiboButtonClicked();
        break;
    case 5:
        commentPageButtonClicked();
        break;
    case 6:
        favouritePageButtonClicked();
        break;
    case 7:
        messagePageButtonClicked();
        break;
    case 8:
        publicStatusesButtonClicked();
        break;
    default:
        qDebug("In ReceiveSignalFromMainWidget:index error!!!");
        break;
    }
}

void SinaWidget::prepare()
{
    this->dealWebkitEventDisconnectThenConnect();
    SinaWeibo *sina = new SinaWeibo(this->account);
    homePageButtonClicked();
    delete sina;
    timer->disconnect();
    timer->stop();
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refreshStatus()));
    timer->setSingleShot(false);
    timer->start(1000*conf->getAccountConf(account->getId(), conf->updateStatusS));//90s
}

void SinaWidget::preHtml()
{
    QObject::disconnect(ui->webView_left->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
                        this, SLOT(addJavaScriptObject()));
    QObject::disconnect(ui->webView_right->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
                        this, SLOT(addJavaScriptObject()));
}

void SinaWidget::showPictueInWidget(QString bigUrl, QString midUrl)
{
    ShowPicture *showPicture = new ShowPicture(bigUrl, midUrl, this);
    showPicture->show();
}

void SinaWidget::refreshStatus()
{
    timer->setInterval(1000*conf->getAccountConf(account->getId(), conf->updateStatusS));
    QWebSettings::clearIconDatabase();//clear qwebview memory cache
    QWebSettings::clearMemoryCaches();

    int preStatusUnread = statusUnread; int preAtMeMentionsUnread = atMeMentionsUnread;
    int preCommentsUnread = commentsUnread; int preDirectMessageUnread = directMessageUnread;
    SinaWeibo sinaWeibo(account);
    sinaWeibo.getUnreadInfo(statusUnread, atMeMentionsUnread, commentsUnread, directMessageUnread, newFollower);
    if((statusUnread - preStatusUnread )> 0)
    {
        sinaWeibo.initHomePageStatus();


        this->homePageHtmlReady = false;
    }
    if((commentsUnread - preCommentsUnread )> 0)
    {
        /*
         API: http://open.t.sina.com.cn/wiki/index.php/Statuses/reset_count
         1------comments
         2------atMe
         3-------directMessage
         4-------newFollower
         */
        sinaWeibo.resetCount(1);
        sinaWeibo.initCommentPageStatus();



        this->commentPageHtmlReady = false;
    }
    if((atMeMentionsUnread - preAtMeMentionsUnread)> 0)
    {
        sinaWeibo.resetCount(2);
        sinaWeibo.initAtMePageStatus();


        this->atMePageHtmlReady = false;
    }
    if((directMessageUnread - preDirectMessageUnread)> 0)
    {
        sinaWeibo.resetCount(3);
        sinaWeibo.initDirectMessagePageStatus();


        this->directMessagePageHtmlReady = false;
    }

//    this->refreshSystemTrayIconTooltip();

    QList<WithU::NotifyObject> messageList;
    if((statusUnread - preStatusUnread)>0)
    {
        WithU::NotifyObject obj;
        obj.type = WithU::HomePageNumber;
        for( int i=0; i<(statusUnread-preStatusUnread); i++)
        {
            Status status = account->homePageStatus.at(i);
            obj.status = status;
            if(!status.getRetweetedId().isEmpty())
            {
                obj.retwStatus = account->homePageRetweeted.value(status.getRetweetedId());
            }
            messageList.append(obj);
        }
    }

    if((commentsUnread - preCommentsUnread)>0)
    {
        WithU::NotifyObject obj;
        obj.type = WithU::CommentPageNumber;
        for( int i=0; i<(commentsUnread-preCommentsUnread); i++)
        {
            Status status = account->commentPageComments.at(i);
            obj.status = status;
            if(!status.getRetweetedId().isEmpty())
            {
                obj.retwStatus = account->commentPageRetweeted.value(status.getRetweetedId());
            }
            messageList.append(obj);
        }
    }

    if((atMeMentionsUnread - preAtMeMentionsUnread)>0)
    {
        WithU::NotifyObject obj;
        obj.type = WithU::AtMePageNumber;
        for( int i=0; i<(atMeMentionsUnread-preAtMeMentionsUnread); i++)
        {
            Status status = account->atMePageStatus.at(i);
            obj.status = status;
            if(!status.getRetweetedId().isEmpty())
            {
                obj.retwStatus = account->atMePageRetweeted.value(status.getRetweetedId());
            }
            messageList.append(obj);
        }
    }

    if((directMessageUnread - preDirectMessageUnread)>0)
    {
        WithU::NotifyObject obj;
        obj.type = WithU::DirectMessagePageNumber;
        for( int i=0; i<(directMessageUnread-preDirectMessageUnread); i++)
        {
            Status status = account->directMessagePageStatus.at(i);
            obj.status = status;
            messageList.append(obj);
        }
    }
    /*
     * 消息提醒
     */
    if(!messageList.isEmpty()&&conf->settings->value(account->getId()+"/"+conf->isNotifyCS, true).toBool())
    {
        /*
        Notifer *notifer = new Notifer(this);
        notifer->setAttribute(Qt::WA_DeleteOnClose);
        notifer->setNotiferContentAndShow(messageList);
        */
    }
}


void SinaWidget::getOthersTimelineByScreenName(QString screenName, int page)
{
    this->preHtml();
    if(page<1)
        page = 1;
    SinaWeibo *sina = new SinaWeibo(account);

    QString xmlContent = sina->getUserTimelineByScreenName(screenName,
                                                           conf->getAccountConf(account->getId(),conf->userWeiboCS), page, 0, 0);
    SinaParserXml sinaParserXml;
    QList<Status> statusList;
    QMap<QString, Status> retwStatusList;
    sinaParserXml.parserStatusXml(xmlContent, statusList, retwStatusList);
    QString pageHtml;
    QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()==(conf->getAccountConf(account->getId(),conf->userWeiboCS)))
    {
        if(page<=1)
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%1\",1)>首页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%2\",2)>下一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(screenName)
                    .arg(screenName);
        }
        else
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%1\",1)>首页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%2\",%3)>上一页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%4\",%5)>下一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(screenName)
                    .arg(screenName)
                    .arg(page-1)
                    .arg(screenName)
                    .arg(page+1);
        }
    }
    else
    {
        if(page<=1)
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%1\",1)>首页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%2\",2)>下一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(screenName)
                    .arg(screenName);
        }
        else
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%1\",1)>首页</a>"
                     "<a href=javascript:void(0) onclick=getUserTimelineByScreenName(\"%2\",%3)>上一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(screenName)
                    .arg(screenName)
                    .arg(page-1);
        }
    }

    contentHtml = sina->userWeiboPageStatusToHtml(statusList, retwStatusList);
    contentHtml.append(pageHtml);

//    QString htmlStr = basicHtml.arg(contentHtml);

//    qDebug(htmlStr.toUtf8());

    if (screenName != account->getScreenName())
        this->setWebviewHtml(basicHtml.arg(contentHtml),Right);
    else
        this->setWebviewHtml(basicHtml.arg(contentHtml),Left);
//    QString countsInJsonFormat = sina->getStatusCountsByJson(statusList);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
//    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void SinaWidget::getMoreHomePageStatus(int page, int feature)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getFriendsTimeline(0, 0, conf->getAccountConf(account->getId(), conf->homeCS),
                                                  page, 0, feature);
    SinaParserXml sinaParserXml;
    QList<Status> statusList; QMap<QString, Status> retwStatusList;
    sinaParserXml.parserStatusXml(xmlContent, statusList, retwStatusList);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(),conf->homeCS)))
    {
        if(page<=1)
        {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreHomePageStatus(2,0)>下一页</a>"
                       "</p>";
        }
        else
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                     "<a href=javascript:void(0) onclick=getMoreHomePageStatus(%1,0)>上一页</a>"
                     "<a href=javascript:void(0) onclick=getMoreHomePageStatus(%2,0)>下一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
    }
    else
    {
        if(page<=1)
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                     "</p>";
        }
        else
        {
            pageHtml="<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                     "<a href=javascript:void(0) onclick=getMoreHomePageStatus(%1,0)>上一页</a>"
                     "</p>";
            pageHtml = pageHtml.arg(page-1);
        }
    }
    contentHtml = sina->homePageStatusToHtml(statusList, retwStatusList);
    contentHtml.append(pageHtml);
    this->setWebviewHtml(basicHtml.arg(contentHtml),Left);
//    QString countsInJsonFormat = sina->getStatusCountsByJson(statusList);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
//    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void SinaWidget::getMoreUserPageStatus(int page, int )
{
    qDebug(account->getScreenName().toLocal8Bit());
    getOthersTimelineByScreenName(account->getScreenName(),page);
}

void SinaWidget::getMoreAtMePageStatus(int page)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getMentions(0, 0, conf->getAccountConf(account->getId(), conf->atMeCS), page);
    SinaParserXml sinaParserXml;
    QList<Status> statusList; QMap<QString, Status> retwStatusMap;
    sinaParserXml.parserStatusXml(xmlContent, statusList, retwStatusMap);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(), conf->atMeCS)))
    {
        if(page<=1)
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(2)>下一页</a></p>";
         else {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(%1)>上一页</a>"
                       "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(%2)>下一页</a></p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
     } else {
         if(page<=1) pageHtml = "<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a></p>";
         else
         {
             pageHtml = "<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a>"
                        "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(%1)>上一页</a></p>";
             pageHtml = pageHtml.arg(page-1);
         }
     }
     contentHtml = sina->atMePageStatusToHtml(statusList, retwStatusMap);
     contentHtml.append(pageHtml);
     this->setWebviewHtml(basicHtml.arg(contentHtml),Left);
//     QString countsInJsonFormat = sina->getStatusCountsByJson(statusList);
     while(!dealWebkitEvent->isDomReady())
     {
         QApplication::processEvents();
     }
 //    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
     delete sina;
}

void SinaWidget::getMoreCommentsPageStatus(int page)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getCommentTimeline(0, 0,
                                                  conf->getAccountConf(account->getId(), conf->commentCS), page);
    SinaParserXml sinaParserXml;
    QList<Status> statusList; QMap<QString, Status> retwStatusMap;
    sinaParserXml.parserCommentTimeline(xmlContent, statusList, retwStatusMap);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(), conf->commentCS)))
    {
        if(page<=1)
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(2)>下一页</a></p>";
        else {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(%1)>上一页</a>"
                       "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(%2)>下一页</a></p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
    } else {
        if(page<=1) pageHtml = "<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a></p>";
        else
        {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(%1)>上一页</a></p>";
            pageHtml = pageHtml.arg(page-1);
        }
    }
    contentHtml = sina->commentPageStatusToHtml(statusList, retwStatusMap);
    contentHtml.append(pageHtml);
    //ui->webView_left->setHtml(basicHtml.arg(contentHtml));
    this->setWebviewHtml(basicHtml.arg(contentHtml),Left);
    delete sina;
}

void SinaWidget::getMoreFavoritePageStatus(int page)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getFavorites(page);
    SinaParserXml sinaParserXml;
    QList<Status> statusList; QMap<QString, Status> retwStatusMap;
    sinaParserXml.parserStatusXml(xmlContent, statusList, retwStatusMap);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(), conf->favoriteCS)))
    {
        if(page<=1)
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(2)>下一页</a></p>";
        else {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(%1)>上一页</a>"
                       "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(%2)>下一页</a></p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
    } else {
        if(page<=1) pageHtml = "<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a></p>";
        else
        {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(%1)>上一页</a></p>";
            pageHtml = pageHtml.arg(page-1);
        }
    }
    contentHtml = sina->favoritePageStatusToHtml(statusList, retwStatusMap);
    contentHtml.append(pageHtml);
    this->setWebviewHtml(basicHtml.arg(contentHtml),Left);
 //   QString countsInJsonFormat = sina->getStatusCountsByJson(statusList);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
   // dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void SinaWidget::getMoreDirectMessagePageStatus(int page)
{
    this->preHtml();
    if(page<1) page=1;
    SinaWeibo *sina = new SinaWeibo(account);
    QString xmlContent = sina->getDirectMessage( 0, 0,
                                                 conf->getAccountConf(account->getId(), conf->directMessageCS), page);
    SinaParserXml sinaParserXml;
    QList<Status> statusList;
    sinaParserXml.parserDirectMessage(xmlContent, statusList);
    QString pageHtml; QString contentHtml;
    if(!statusList.isEmpty()&&statusList.length()>=(conf->getAccountConf(account->getId(), conf->directMessageCS)))
    {
        if(page<=1)
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(2)>下一页</a></p>";
        else {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(%1)>上一页</a>"
                       "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(%2)>下一页</a></p>";
            pageHtml = pageHtml.arg(page-1).arg(page+1);
        }
    } else {
        if(page<=1) pageHtml = "<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a></p>";
        else
        {
            pageHtml = "<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a>"
                       "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(%1)>上一页</a></p>";
            pageHtml = pageHtml.arg(page-1);
        }
    }
    contentHtml = sina->directMessagePageStatusToHtml(statusList);
    contentHtml.append(pageHtml);
    //ui->webView_left->setHtml(basicHtml.arg(contentHtml));
    this->setWebviewHtml(basicHtml.arg(contentHtml),Left);
    delete sina;
}

void SinaWidget::addJavaScriptObject()
{
    ui->webView_left->page()
            ->mainFrame()
            ->addToJavaScriptWindowObject("dealWebkitEvent", this->dealWebkitEvent);
    ui->webView_right->page()
            ->mainFrame()
            ->addToJavaScriptWindowObject("dealWebkitEvent",this->dealWebkitEvent);
}

void SinaWidget::dealWebkitEventDisconnectThenConnect()
{
    QObject::connect(dealWebkitEvent, SIGNAL(getUserTimelineByScreenNameSignal(QString, int)),
                     this, SLOT(getOthersTimelineByScreenName(QString, int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreHomePageStatusSignal(int,int)),
                     this, SLOT(getMoreHomePageStatus(int,int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreUserPageStatusSignal(int,int)),
                     this, SLOT(getMoreUserPageStatus(int,int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreAtMePageStatusSignal(int)),
                     this, SLOT(getMoreAtMePageStatus(int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreCommentsPageStatusSignal(int)),
                     this, SLOT(getMoreCommentsPageStatus(int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreFavoritePageStatusSignal(int)),
                     this, SLOT(getMoreFavoritePageStatus(int)));
    QObject::connect(dealWebkitEvent, SIGNAL(getMoreDirectMessagePageStatusSignal(int)),
                     this, SLOT(getMoreDirectMessagePageStatus(int)));
    QObject::connect( dealWebkitEvent, SIGNAL(showBigPicture(QString, QString)),
                      this, SLOT(showPictueInWidget(QString,QString)));
    QObject::connect(dealWebkitEvent ,SIGNAL(forwardToOtherClientSignal(QString)),
                     this,SLOT(forwardToOtherClientSlot(QString)));

}

void SinaWidget::newWeiboButtonClicked()
{
    if (this->pStatusWidget == NULL)
    {
        pStatusWidget = new StatusWidget(this->account);
        pStatusWidget->setWindowTitle(tr("发新微博"));
    }
    pStatusWidget->freeSendButton();
    pStatusWidget->clearContent();
    pStatusWidget->show();
}

void SinaWidget::homePageButtonClicked()
{
    this->preHtml();
    SinaWeibo *sina = new SinaWeibo(account);
    if(!homePageHtmlReady)
    {
        if(!homePageStatusReady)
        {
            sina->initHomePageStatus();
            homePageStatusReady = true;
        }
        QString pageHtml = "<p><a href=javascript:void(0) onclick=getMoreHomePageStatus(1,0)>首页</a>"
                   "<a href=javascript:void(0) onclick=getMoreHomePageStatus(2,0)>下一页</a>"
                   "</p>";
        homePageHtml = basicHtml
                       .arg(sina->homePageStatusToHtml(
                               account->homePageStatus,
                               account->homePageRetweeted)
                            );
        homePageHtml.append(pageHtml);
        homePageHtmlReady = true;

        this->statusUnread=0;
 //       this->refreshSystemTrayIconTooltip();
    }
    this->setWebviewHtml(homePageHtml,Left);

//    QString countsInJsonFormat = sina->getStatusCountsByJson(account->homePageStatus);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
//    dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void SinaWidget::myWeiboPageButtonClicked()
{
    this->preHtml();
    SinaWeibo *sina = new SinaWeibo(account);
    if(!myWeiboPageHtmlReady)
    {
        if(!myWeiboPageStatusReady)
        {
            sina->initUserWeiboPageStatus();
        }
        myWeiboPageHtml = basicHtml
                          .arg(sina->userWeiboPageStatusToHtml(
                                  account->userWeiboPageStatus,
                                  account->userWeiboPageRetweeted)
                               );
        myWeiboPageHtml.append( "<p><a href=javascript:void(0) onclick=getMoreUserPageStatus(1,0)>首页</a>"
                                 "<a href=javascript:void(0) onclick=getMoreUserPageStatus(2,0)>下一页</a>"
                                 "</p>");
    }
    this->setWebviewHtml(myWeiboPageHtml,Left);
 //   QString countsInJsonFormat = sina->getStatusCountsByJson(account->userWeiboPageStatus);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
  //  dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;

}

void SinaWidget::atMePageButtonClicked()
{
    this->preHtml();
    SinaWeibo *sina = new SinaWeibo(account);
    if(!atMePageHtmlReady)
    {
        if(!atMePageStatusReady)
        {
            sina->initAtMePageStatus();
            atMePageStatusReady = true;
        }
        atMePageHtml = basicHtml
                       .arg(sina->atMePageStatusToHtml(
                               account->atMePageStatus,
                               account->atMePageRetweeted)
                            );
        if(account->atMePageStatus.length()>=conf->getAccountConf(account->getId(), conf->atMeCS))
            atMePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a>"
                                "<a href=javascript:void(0) onclick=getMoreAtMePageStatus(2)>下一页</a></p>");
        else
            atMePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreAtMePageStatus(1)>首页</a></p>");
        atMePageHtmlReady = true;

        this->atMeMentionsUnread = 0;
//        this->refreshSystemTrayIconTooltip();
    }
    this->setWebviewHtml(atMePageHtml,Left);
  //  QString countsInJsonFormat = sina->getStatusCountsByJson(account->atMePageStatus);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
  //  dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void SinaWidget::commentPageButtonClicked()
{
    this->preHtml();
    if(!commentPageHtmlReady)
    {
        SinaWeibo *sina = new SinaWeibo(account);
        if(!commentPageStatusReady)
        {
            sina->initCommentPageStatus();
            commentPageStatusReady = true;
        }
        commentPageHtml = basicHtml
                          .arg(sina->commentPageStatusToHtml(
                                  account->commentPageComments,
                                  account->commentPageRetweeted)
                               );
        if(account->commentPageComments.length()>=conf->getAccountConf(account->getId(), conf->commentCS))
            commentPageHtml.append("<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a>"
                                   "<a href=javascript:void(0) onclick=getMoreCommentsPageStatus(2)>下一页</a></p>");
        else
            commentPageHtml
                    .append("<p><a href=javascript:void(0) onclick=getMoreCommentsPageStatus(1)>首页</a></p>");
        commentPageHtmlReady = true;
        delete sina;

        this->commentsUnread = 0;
//        this->refreshSystemTrayIconTooltip();
    }
    //ui->webView_left->setHtml(commentPageHtml);
    this->setWebviewHtml(commentPageHtml,Left);
}

void SinaWidget::favouritePageButtonClicked()
{
    this->preHtml();
    SinaWeibo *sina = new SinaWeibo(account);
    if(!favoritePageHtmlReady)
    {
        if(!favoritePageStatusReady)
        {
            sina->initFavoritePageStatus();
        }
        favoritePageHtml = basicHtml
                           .arg(sina->favoritePageStatusToHtml(
                                   account->favoritesPageStatus,
                                   account->favoritesPageRetweeted)
                                );
        if(account->favoritesPageStatus.length()>=conf->getAccountConf(account->getId(), conf->favoriteCS))
            favoritePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a>"
                                    "<a href=javascript:void(0) onclick=getMoreFavoritePageStatus(2)>下一页</a></p>");
        else
            favoritePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreFavoritePageStatus(1)>首页</a></p>");
    }
    this->setWebviewHtml(favoritePageHtml,Left);
//    QString countsInJsonFormat = sina->getStatusCountsByJson(account->favoritesPageStatus);
    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }
 //   dealWebkitEvent->sendStatusesCounts(countsInJsonFormat);
    delete sina;
}

void SinaWidget::messagePageButtonClicked()
{
    this->preHtml();
    if(!directMessagePageHtmlReady)
    {
        SinaWeibo *sina = new SinaWeibo(account);
        if(!directMessagePageStatusReady)
        {
            sina->initDirectMessagePageStatus();
            directMessagePageStatusReady = true;
        }
        directMessagePageHtml = basicHtml
                                .arg(sina->directMessagePageStatusToHtml(
                                        account->directMessagePageStatus));
        if(account->directMessagePageStatus.length()>=conf->getAccountConf(account->getId(), conf->directMessageCS))
            directMessagePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a>"
                                    "<a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(2)>下一页</a></p>");
        else
            directMessagePageHtml.append("<p><a href=javascript:void(0) onclick=getMoreDirectMessagePageStatus(1)>首页</a></p>");
        this->directMessagePageHtmlReady = true;
        delete sina;

        this->directMessageUnread = 0;
//        this->refreshSystemTrayIconTooltip();
    }

    //ui->webView_left->setHtml(directMessagePageHtml);
    this->setWebviewHtml(directMessagePageHtml,Left);
}

void SinaWidget::configureButtonClicked()
{

}

void SinaWidget::publicStatusesButtonClicked()
{
    this->preHtml();

    SinaWeibo *sina = new SinaWeibo(account);
    if(!publicStatusesHtmlReady)
    {
        if(!publicStatusesReady)
        {
            sina->initPublicStatus();
            publicStatusesReady = true;
        }

        QString xmlContent = sina->getPublicStatus();

        SinaParserXml sinaParserXml;
        sinaParserXml.parserStatusXml(xmlContent, account->publicStatus, account->publicRetweeted);

        publicStatusesHtml = basicHtml
                       .arg(sina->homePageStatusToHtml(account->publicStatus,account->publicRetweeted)
                            );
        publicStatusesHtmlReady = true;


    }
    this->setWebviewHtml(publicStatusesHtml,Left);

    while(!dealWebkitEvent->isDomReady())
    {
        QApplication::processEvents();
    }

    delete sina;


}

void SinaWidget::systemTrayIconAction(QSystemTrayIcon::ActivationReason reason)
{
    if(reason==QSystemTrayIcon::DoubleClick)
    {
        this->showNormal();
        QApplication::alert(this,1000);
    }
    if(reason==QSystemTrayIcon::Trigger)
    {
        this->showNormal();
        QApplication::alert(this,1000);
    }
}

void SinaWidget::createSystemTrayIcon()
{

    this->systemTrayIcon = new QSystemTrayIcon(this);
    this->restoreAction = new QAction(tr("打开主面板"), this);
    QObject::connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
    QObject::connect(systemTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
                     this, SLOT(systemTrayIconAction(QSystemTrayIcon::ActivationReason)));
    this->quitAction = new QAction(tr("退出"), this);
    QObject::connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
    this->systemTrayMenu = new QMenu(this);
    this->systemTrayMenu->addAction(restoreAction);
    this->systemTrayMenu->addAction(quitAction);
    this->systemTrayIcon->setContextMenu(this->systemTrayMenu);
    this->systemTrayIcon->setIcon(QIcon(":/logo/images/qlisa.png"));
    this->systemTrayIcon->setVisible(true);

}

void SinaWidget::refreshSystemTrayIconTooltip()
{
    QString msg = "未读微博%1条,\n新评论%2条,\n新私信%3条,\n有%4条微博提到我";
    msg = msg
          .arg(statusUnread)
          .arg(commentsUnread)
          .arg(directMessageUnread)
      //    .arg(newFollower)
          .arg(atMeMentionsUnread);
    systemTrayIcon->setToolTip(msg);
}


void SinaWidget::setWebviewHtml(QString html,WebViewPos pos)
{
    QWebView *pWebView = NULL;
    if (pos == Left)
        pWebView = ui->webView_left;
    else
        pWebView = ui->webView_right;

    pWebView->deleteLater();

    QWebPage *oldPage = pWebView->page();
    if (oldPage != NULL)
        oldPage->deleteLater();
    QWebPage *newPage = new QWebPage(this);

    pWebView->setPage(newPage);

    delete newPage;
    QObject::connect( pWebView->page()->mainFrame(),
                      SIGNAL(javaScriptWindowObjectCleared()),
                      this,
                      SLOT(addJavaScriptObject())
                      );

    QObject::connect(ui->webView_right->page()->mainFrame(),
                     SIGNAL(javaScriptWindowObjectCleared()),
                     this,
                     SLOT(addJavaScriptObject()));

    DealWebkitEvent *old = this->dealWebkitEvent;
    this->dealWebkitEvent = new DealWebkitEvent(account, this);
    old->deleteLater();

    this->dealWebkitEventDisconnectThenConnect();
    this->addJavaScriptObject();
    this->dealWebkitEvent->setDomReady(false);
    pWebView->setHtml(html);
/*
    if (pos == Left)
        qDebug("les\n"+html.toLocal8Bit());
        */
}

void SinaWidget::updateIcon(QPixmap *pixmap, int unreadCount)
{
    QPainter painter(pixmap);
    painter.setPen(Qt::red);
    QFont font("Arial", 10, 10);
    font.setBold(true);
    painter.setFont(font);
    painter.drawText(0, 0, 32, 32, Qt::AlignCenter, QString::number(unreadCount), 0);
}

QString SinaWidget::getImageUrl(){

    if (this->account == NULL){
        return QString("");
    }
    else{
        return this->account->getProfileImageUrl();
    }

}

void SinaWidget::getUserInfo()
{
    if (this->otherAccount == NULL)
    {
        this->otherAccount = new Account;
    }
    SinaWeibo *pSina = new SinaWeibo(this->account);

    pSina->getSinaAccountByID(*(this->otherAccount),"1608069231");

    delete pSina;
}

void SinaWidget::forwardToOtherClientSlot(QString str)
{
    emit forwardToOtherClientSignal(str);
}

void SinaWidget::forward_from_otherClient(QString str)
{
    if (str.length() > 135)
    {
        str = str.left(135);
    }
    if (pStatusWidget == NULL)
    {
        pStatusWidget = new StatusWidget(this->account);
    }

    pStatusWidget->freeSendButton();
    pStatusWidget->clearContent();
    pStatusWidget->setText(str);
    pStatusWidget->show();
}

QPixmap SinaWidget::getPixmapFromUrl(QUrl url)
{
    QNetworkRequest request; 
    QString urlStr = url.toString().replace(QRegExp("/50/"),"/180/");
    url.setUrl(urlStr);
    request.setUrl(url);
    Http *http = new Http(this);
    QPixmap image = http->getImageFromUrl(request);
    return image;
}

void SinaWidget::changeSelectedPixmap(int index, int type)
{
    QString styleSheet="QWidget#%1%2{background-image:url(:/images/leftselected.png)}";
    if (type == 0)//remove
    {
        QString tmp = "";
        switch (index)
        {
        case 1:
            ui->left_1->setStyleSheet(tmp);
            break;
        case 2:
            ui->left_2->setStyleSheet(tmp);
            break;
        case 3:
            ui->left_3->setStyleSheet(tmp);
            break;
        case 4:
            ui->left_4->setStyleSheet(tmp);
            break;
        case 5:
            ui->left_5->setStyleSheet(tmp);
            break;
        case 6:
            ui->left_6->setStyleSheet(tmp);
            break;
        case 7:
            ui->left_7->setStyleSheet(tmp);
            break;
        case 8:
            ui->left_8->setStyleSheet(tmp);
            break;
        }
    }
    else if (type == 1)//add
    {
        styleSheet = styleSheet.arg("left_").arg(QString::number(index));
        switch (index)
        {
        case 1:
            ui->left_1->setStyleSheet(styleSheet);
            break;
        case 2:
            ui->left_2->setStyleSheet(styleSheet);
            break;
        case 3:
            ui->left_3->setStyleSheet(styleSheet);
            break;
        case 4:
//            ui->left_4->setStyleSheet(styleSheet);
            break;
        case 5:
            ui->left_5->setStyleSheet(styleSheet);
            break;
        case 6:
            ui->left_6->setStyleSheet(styleSheet);
            break;
        case 7:
            ui->left_7->setStyleSheet(styleSheet);
            break;
        case 8:
            ui->left_8->setStyleSheet(styleSheet);
            break;
    }
    }
    else{
        qDebug("changeSelectedPixmap type error!!!");
    }

}

void SinaWidget::closeEvent(QCloseEvent *e)
{
    qDebug("closeEvent");
}
